#include "nixie_tube.h"
#include "c51.h"

u8 buffer[9] = {
    Zero, Nil, Nil, Nil, Nil, Nil, Nil, Nil, Nil,
};

/*
 * 示例 点亮 6
 *     a(11)
 * f(10)   b(7)
 *     g(5)
 * e(1)    c(4)
 *     d(2)
 *              dp(3)
 *
 *  a b c d   e  f g dp
 *  1 0 1 1   1  1 1 0
 * 11 7 4 2   1 10 5 3
 * 然后从 dp 开始就是 0111 1101
 */
u8 num[] = {
    0b00111111, 0b00000110, 0b01011011, 0b01001111, 0b01100110,
    0b01101101, 0b01111101, 0b00100111, 0b01111111, 0b01101111,
    0,          0b01000000, 0b10000000,
};

void nixie_tube_turn(u8 location, Num number) {
  P0 = 0;
  switch (location) {
  case 1:
    P2_4 = 0;
    P2_3 = 0;
    P2_2 = 0;
    break;
  case 2:
    P2_4 = 0;
    P2_3 = 0;
    P2_2 = 1;
    break;
  case 3:
    P2_4 = 0;
    P2_3 = 1;
    P2_2 = 0;
    break;
  case 4:
    P2_4 = 0;
    P2_3 = 1;
    P2_2 = 1;
    break;
  case 5:
    /*
     * LED8 LED7 LED6 LED5 LED4 LED3 LED2 LED1
     * P22(A) P23(B) P24(C)
     * 0b1     0     0
     *   (P24) (P23) (P22)
     */
    P2_4 = 1;
    P2_3 = 0;
    P2_2 = 0;
    break;
  case 6:
    P2_4 = 1;
    P2_3 = 0;
    P2_2 = 1;
    break;
  case 7:
    P2_4 = 1;
    P2_3 = 1;
    P2_2 = 0;
    break;
  case 8:
    P2_4 = 1;
    P2_3 = 1;
    P2_2 = 1;
    break;
  }
  P0 = num[number];
}

void nixie_tube_loop(void) {
  static u8 i = 1;
  nixie_tube_turn(i, buffer[i]);
  i++;
  if (i > 8) {
    i = 1;
  }
}

void nixie_tube_set(u8 location, Num num) { buffer[location] = num; }
